<template>
  <page-header-wrapper :title="false">
    <div class="Role">
      <a-spin tip="加载中..." class="position" v-if="roleLoading"> </a-spin>
      <a-modal
        width="65%"
        v-model="detailsVisible"
        title="详情信息"
        @cancel="() => (this.detailsVisible = false)"
        destroyOnClose
      >
        <div id="modalContent">
          <div class="Row">
            <p class="lefeLabel">设备编码：</p>
            <p class="rightText">{{ form.chargingCabinetCode }}</p>
          </div>
          
          <div class="Row">
            <p class="lefeLabel">类型：</p>
            <p class="rightText">{{ formatterType(form.type) }}</p>
          </div>
          <div class="Row">
            <p class="lefeLabel">流水号：</p>
            <p class="rightText">{{ form.txnNo }}</p>
          </div>
          <div class="Row">
            <p class="lefeLabel">流水时间：</p>
            <p class="rightText">{{ formatterTime(form.txnNoTime) }}</p>
          </div>
          <div class="Row">
            <p class="lefeLabel">数据时间：</p>
            <p class="rightText">{{ formatterTime(form.createTime) }}</p>
          </div>
          <div class="Row">
            <p class="lefeLabel">消息类型：</p>
            <p class="rightText">{{ formatterMessageType(form.msgType) }}</p>
          </div>
          <div class="Row">
            <p class="lefeLabel">内容：</p>
            <!-- <p class="rightText">{{ form.payload }}</p> -->
          </div>
          <div class="jsonconts">
            <div class="jsonContent">
              <!-- @json-change="onJsonChange"
                @json-save="onJsonSave"
                @has-error="onError" -->
              <vue-json-editor style="height: 100%" v-model="form.payload" :showBtns="false" mode="text" />
            </div>
            <div class="jsonContent">
              <vue-json-editor style="height: 100%" v-model="form.transpayload" :showBtns="false" mode="text" />
            </div>
          </div>
          <!-- <div class="Row">
            <p class="lefeLabel">解析后数据：</p>
            <p class="rightText"> {{ form.dataJson }} </p>
          </div>
          <div class="Row">
            <p class="lefeLabel">异常原因：</p>
            <p class="rightText"> {{ form.cause }} </p>
          </div> -->
        </div>
        <template slot="footer">
          <Button
            type="reset"
            label="关闭"
            @click="
              () => {
                this.detailsVisible = false;
              }
            "
          ></Button>
        </template>
      </a-modal>
      <typicalSearch
        ref="insideSearch"
        :searchConfig="searchConfig"
        @searchMethod="getTableData"
        @clearMethod="clearSearchConfig"
      ></typicalSearch>
      <div class="table">
        <div class="tableTitle">
          <div class="title">报文日志记录</div>
        </div>
        <div class="tableList">
          <typicalTable
            ref="insideTable"
            :tableConfig="tableConfig"
            :tableData="tableData"
            @getTableData="getTableData"
          >
            <template v-slot="slotProps">
              <Button label="查看" @click="handleEdit(slotProps.record)"></Button>
            </template>
          </typicalTable>
        </div>
      </div>
    </div>
  </page-header-wrapper>
</template>
<script>
import moment from 'moment';
import typicalSearch from '@/components/typicalSearch';
import typicalTable from '@/components/typicalTable';
import Input from '@/components/typicalControl/Input';
import Select from '@/components/typicalControl/select';
import datePicker from '@/components/typicalControl/datePicker';
import Button from '@/components/typicalControl/button';
import { getListEnumsJson } from '@/utils/frequentInterface';

import { equipmentMonitoring, samphores } from '@/api/cabin';
import vueJsonEditor from 'vue-json-editor';

import notification from 'ant-design-vue/es/notification';

export default {
  name: 'AlarmInformation',
  components: {
    typicalSearch: typicalSearch,
    typicalTable: typicalTable,
    Input: Input,
    datePicker: datePicker,
    Select: Select,
    Button: Button,
    vueJsonEditor,
  },
  data() {
    return {
      roleLoading: false, // 加载表格的loading
      detailsVisible: false,
      // 搜索组件配置
      searchConfig: {
        formItemList: [
          {
            type: 'input',
            prop: 'searchCabinetCode',
            value: undefined,
            label: '充电柜编码',
          },
          {
            type: 'inputNum',
            prop: 'searchTxnNo',
            value: undefined,
            label: '流水号',
            min: 0
          },
          {
            type: 'select',
            prop: 'searchMsgType',
            value: undefined,
            label: '消息类型',
            multiple: 'multiple',
            optList: [],
          },
          {
            type: 'datePicker',
            prop: 'searchTableName',
            valueFormat: 'YYYYMMDD',
            value: moment(new Date()).format('YYYYMMDD'),
            label: '日志日期',
            change: this.datePickerChange,
          },
          {
            type: 'rangeTimePicker',
            prop: 'searchLogTimeBegin&searchLogTimeEnd',
            format: 'HH:mm:ss',
            valueFormat: 'HH:mm:ss',
            showTime: true,
            value: [
              moment(new Date()).hours(0).minutes(0).seconds(0).format('HH:mm:ss'),
              moment(new Date()).hours(23).minutes(59).seconds(59).format('HH:mm:ss'),
            ],
            label: '数据时间',
          },
          // {
          //   type: 'input',
          //   prop: 'searchLogCmd',
          //   value: undefined,
          //   label: '命令字'
          // }
          // ,
          // {
          //   type: 'selectTree',
          //   prop: 'a',
          //   value: undefined,
          //   label: '组织机构'
          // },
          // {
          //   type: 'input',
          //   prop: 'c',
          //   value: '',
          //   label: '故障名称'
          // }
        ],
        parent: this,
      },
      // 列表组件配置
      tableConfig: {
        columns: [
          {
            title: '充电柜编码',
            dataIndex: 'chargingCabinetCode',
            ellipsis: true,
          },
          {
            title: '类型',
            dataIndex: 'type',
            ellipsis: true,
            customRender: this.formatterType,
          },
          {
            title: '消息类型',
            dataIndex: 'msgType',
            ellipsis: true,
            customRender: this.formatterMessageType,
          },
          {
            title: '流水号',
            dataIndex: 'txnNo',
            ellipsis: true,
          },
          {
            title: '流水时间',
            dataIndex: 'txnNoTime',
            ellipsis: true,
            customRender: this.formatterTime,
          },
          {
            title: '数据时间',
            dataIndex: 'createTime',
            ellipsis: true,
            customRender: this.formatterTime,
          },
          {
            title: '操作',
            scopedSlots: { customRender: 'action' },
            ellipsis: true,
            width: '120px',
          },
        ],
        pageSize: this.$store.state.user.defaultPaginationPagesize,
        pageSizeOptions: this.$store.state.user.defaultPaginationOptions,
        parent: this,
      },
      // 列表组件数据
      tableData: {
        records: [],
        total: 0,
      },
      form: {
        cabinetCode: '',
        logTime: '',
        type: '',
        logCmd: '',
        original: '',
        decrypt: '',
        dataJson: '',
        cause: '',
        payload: '',
        transpayload: '',
      },
      enumsType: ['CHARGING_CABINET_MQTT_LOG_TYPE'],
      enumsTypeJson: {},
      hasJsonFlag: true, // json是否验证通过
      // json数据
      resultInfo: {
        employees: [
          {
            firstName: 'Bill',
            lastName: 'Gates',
          },
          {
            firstName: 'George',
            lastName: 'Bush',
          },
          {
            firstName: 'Thomas',
            lastName: 'Carter',
          },
        ],
      },
      samphoreList: [], //信号量list
    };
  },
  created() {
    // this.enumsTypeJson = getListEnumsJson(this.enumsType, this.updateOption);
    getListEnumsJson().then((res) => {
      this.enumsTypeJson = res;
      this.updateOption();
    });
    this.getSamphore();
  },
  mounted() {
    this.$refs.insideSearch.searchInfo();
  },
  methods: {
    getListEnumsJson,
    /**
     * [updateOption 更新选项卡选项]
     * @return {[type]} [description]
     */
    updateOption() {
      for (var i = 0; i < this.searchConfig.formItemList.length; i++) {
        if (this.searchConfig.formItemList[i].prop == 'searchMsgType') {
          this.searchConfig.formItemList[i].optList = [];
          const arr = this.enumsTypeJson['MQTT_MESSAGE_TYPE'];
          for (var k = 0; k < arr.length; k++) {
            this.searchConfig.formItemList[i].optList.push(arr[k]);
          }
          break;
        }
      }
    },
    getSamphore() {
      samphores('/all', 'get').then((res) => {
        this.samphoreList = res.data;
      });
    },
    /**
     * [datePickerChange 日志日期变动]
     * @param  {[type]} val         [控件返回值]
     * @param  {[type]} searchParam [search组件的searchParam]
     * @return {[type]}             [description]
     */
    datePickerChange(val, searchParam) {
      var i;
      if (val) {
        var time = val.split('');
        time.splice(6, 0, '-');
        time.splice(4, 0, '-');
        time = time.join('');
        const time1 = moment(time, 'YYYY-MM-DD').hours(0).minutes(0).seconds(0);
        const time2 = moment(time, 'YYYY-MM-DD').hours(23).minutes(59).seconds(59);
        for (i = 0; i < this.searchConfig.formItemList.length; i++) {
          if (this.searchConfig.formItemList[i].prop === 'searchLogTimeBegin&searchLogTimeEnd') {
            this.searchConfig.formItemList[i].type = 'rangeTimePicker';
            // this.searchConfig.formItemList[i].value = [time1.format('YYYY-MM-DD HH:mm:ss'), time2.format('YYYY-MM-DD HH:mm:ss')];
            this.searchConfig.formItemList[i].value = [time1.format('HH:mm:ss'), time2.format('HH:mm:ss')];
            break;
          }
        }
      } else {
        for (i = 0; i < this.searchConfig.formItemList.length; i++) {
          if (this.searchConfig.formItemList[i].prop === 'searchLogTimeBegin&searchLogTimeEnd') {
            // this.searchConfig.formItemList[i].type = 'rangeDatePicker';
            this.searchConfig.formItemList[i].value = [
              moment(new Date()).hours(0).minutes(0).seconds(0).format('HH:mm:ss'),
              moment(new Date()).hours(23).minutes(59).seconds(59).format('HH:mm:ss'),
              // moment(new Date()).hours(0).minutes(0).seconds(0).format('YYYY-MM-DD HH:mm:ss'),
              // moment(new Date()).hours(23).minutes(59).seconds(59).format('YYYY-MM-DD HH:mm:ss'),
            ];
            break;
          }
        }
      }
      delete searchParam['searchLogTimeBegin&searchLogTimeEnd'];
      this.$refs.insideSearch.Initialization(searchParam);
    },
    clearSearchConfig() {
      for (var i = 0; i < this.searchConfig.formItemList.length; i++) {
        if (this.searchConfig.formItemList[i].prop === 'searchLogTimeBegin&searchLogTimeEnd') {
          // this.searchConfig.formItemList[i].type = 'rangeDatePicker';
          this.searchConfig.formItemList[i].value = [
            moment(new Date()).hours(0).minutes(0).seconds(0).format('HH:mm:ss'),
            moment(new Date()).hours(23).minutes(59).seconds(59).format('HH:mm:ss'),
          ];
          break;
        }
      }
      this.$refs.insideSearch.Initialization();
    },
    /**
     * [getTableData 获取表格数据]
     * @param  {[type]} searchParam [搜索条件]
     * @return {[type]}             [description]
     */
    getTableData(searchParam) {
      if (!searchParam) throw new Error('getTableData 没有入参搜索条件！');
      // 20220211z 处理先选日志日期，数据时间自动补上日期
      // if (searchParam.searchTableName) {
      // const str = searchParam.searchTableName + '';
      // const data = str.slice(0, 4) + '-' + str.slice(4, 6) + '-' + str.slice(6) + ' ';
      // searchParam.searchLogTimeBegin = searchParam.searchLogTimeBegin;
      // searchParam.searchLogTimeEnd = searchParam.searchLogTimeEnd;
      // }
      if (!searchParam.searchTableName) {
        notification.error({
          message: '提示',
          description: '请选择日志日期',
        });
        return;
      } else if (!searchParam.searchLogTimeBegin) {
        notification.error({
          message: '提示',
          description: '请选择数据时间',
        });
        return;
      }
      this.roleLoading = true;

      let searchDate = searchParam.searchTableName ? moment(searchParam.searchTableName).format('YYYY-MM-DD') : '';

      let params = {
        pageNum: searchParam.pageNumber,
        pageSize: searchParam.pageSize,
        cabinetCode: searchParam.searchCabinetCode,
        chargingBeginTime: searchParam.searchLogTimeBegin,
        chargingEndTime: searchParam.searchLogTimeEnd,
        msgType: searchParam.searchMsgType&&searchParam.searchMsgType.length>0?searchParam.searchMsgType:undefined,
        txnNo: searchParam.searchTxnNo,
        startDate: searchDate,
      };

      equipmentMonitoring('/selectMessageLog', 'post', params)
        .then((res) => {
          if (res.content) {
            let datas = res.content;
            datas.forEach(item=>item.txnNoTime = item.txnNo ? Number(item.txnNo) :'');
            
            let params = {
              records: datas,
              total: Number(res.totalElements),
            };
            this.tableData = params;
          } else {
            this.tableData.records = [];
            this.tableData.total = 0;
          }
        })
        .finally(() => {
          this.roleLoading = false;
        });
    },
    /**
     * [initializationForm 初始化form数据]
     * @return {[type]} [description]
     */
    initializationForm() {
      return {
        cabinetCode: '',
        logTime: '',
        type: '',
        logCmd: '',
        original: '',
        decrypt: '',
        dataJson: '',
        cause: '',
      };
    },
    /**
     * [handleEdit 查看]
     * @param  {[type]} row [单行数据]
     * @return {[type]}     [description]
     */
    handleEdit(row) {
      this.form = this.initializationForm();
      this.form = Object.assign(this.form, row);
      this.form.payload = JSON.parse(row.payload);
      this.form.transpayload = JSON.parse(row.payload);
      switch (this.form.transpayload.msgType) {
        case 310:
          this.form.transpayload.attrList.forEach((item) => {
            this.samphoreList.forEach((pp) => {
              if (item.id == pp.code) {
                item.name = pp.name;
              }
            });
          });
          break;
        case 410:
          this.form.transpayload.alarmList.forEach((item) => {
            this.samphoreList.forEach((pp) => {
              if (item.id == pp.code) {
                item.name = pp.name;
              }
            });
          });
          break;
        case 500:
          this.form.transpayload.paramList.forEach((item) => {
            this.samphoreList.forEach((pp) => {
              if (item.id == pp.code) {
                item.name = pp.name;
              }
            });
          });
          break;
      }

      this.detailsVisible = true;
    },
    formatterTime(val) {
      return val ? moment(val).format('YYYY-MM-DD HH:mm:ss') : '';
    },
    /**
     * [formatterType 状态枚举显示]
     * @param  {[type]} val [description]
     * @return {[type]}     [description]
     */
    formatterType(val) {
      var result = '';
      if (val && this.enumsTypeJson['CHARGING_CABINET_MQTT_LOG_TYPE']) {
        for (var i = 0; i < this.enumsTypeJson['CHARGING_CABINET_MQTT_LOG_TYPE'].length; i++) {
          if (val === this.enumsTypeJson['CHARGING_CABINET_MQTT_LOG_TYPE'][i].code) {
            result = this.enumsTypeJson['CHARGING_CABINET_MQTT_LOG_TYPE'][i].name;
            break;
          }
        }
      }
      return result;
    },
    formatterMessageType(val) {
      var result = val;
      if (this.enumsTypeJson['MQTT_MESSAGE_TYPE']) {
        for (var i = 0; i < this.enumsTypeJson['MQTT_MESSAGE_TYPE'].length; i++) {
          if (val == this.enumsTypeJson['MQTT_MESSAGE_TYPE'][i].code) {
            result = this.enumsTypeJson['MQTT_MESSAGE_TYPE'][i].name;
            break;
          }
        }
      }
      return result;
    },
    onJsonChange(value) {
      console.log('更改value:', value);
      // 实时保存
      this.onJsonSave(value);
    },
    onJsonSave(value) {
      // console.log('保存value:', value);
      this.resultInfo = value;
      this.hasJsonFlag = true;
    },
    onError(value) {
      console.log('json错误了value:', value);
      this.hasJsonFlag = false;
    },
  },
};
</script>

<style lang="less" scoped>
.Role {
  width: 100%;
  height: calc(100vh - 150px);
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  position: relative;
  .position {
    width: 100%;
    height: 100%;
    background: white;
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 999;
  }
  .table {
    flex: 1;
    background: white;
    border-radius: 5px;
    display: flex;
    flex-direction: column;
    .tableTitle {
      width: 100%;
      height: 64px;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #ececec;
      padding: 0 20px;
      margin-bottom: 10px;
      .title {
        width: 80%;
        height: 100%;
        display: flex;
        align-items: center;
        font-size: 18px;
        font-weight: 550;
      }
      .addButton {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: flex-end;
      }
    }
    .tableList {
      // max-height: calc(100vh - 380px);
      // overflow: auto;
      /deep/ .tableScroll {
        max-height: calc(100vh - 380px);
        overflow: auto;
      }
    }
  }
}
#modalContent {
  width: 100%;
  height: 700px;
  overflow: auto;
  position: relative;
}
/deep/ .jsoneditor-poweredBy {
  display: none;
}

/deep/ .jsoneditor-vue {
  height: 100%;
}
/deep/ textarea.jsoneditor-text {
  font-size: 16px;
  line-height: 20px;
}
.jsonconts {
  display: flex;
}
/deep/ .ant-input-number-handler-wrap{
  display: none;
}
</style>
<style scoped>
.Row {
  position: relative;
  overflow: hidden;
  clear: both;
}
.lefeLabel {
  float: left;
  width: 120px;
  text-align: right;
}
.rightText {
  float: left;
  width: -webkit-calc(100% - 130px);
  width: -moz-calc(100% - 130px);
  width: calc(100% - 130px);
  margin-left: 5px;
  margin-bottom: 10px;
  font-size: 16px;
  color: #000000;
}
.jsonContent {
  width: 48%;
  height: 500px;
  margin: 0 1%;
}

</style>
